package com.tuniu.agents.evaluators.common;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.tuniu.agents.evaluator.IEvaluator;

/**
 * Evaluator Registry
 * Used for managing and retrieving different types of evaluators
 */
@Component
public class EvaluatorRegistry {
    
    private final Map<String, IEvaluator<?>> evaluatorMap = new ConcurrentHashMap<>();
    
    @Autowired
    private ApplicationContext applicationContext;
    
    @Autowired
    public void registerEvaluators() {
        // Get all beans of type IEvaluator
        Map<String, IEvaluator> evaluatorBeans = applicationContext.getBeansOfType(IEvaluator.class);
        
        // Register all evaluators
        evaluatorBeans.values().forEach(this::registerEvaluator);
    }
    
    /**
     * Register an evaluator
     * @param evaluator Evaluator instance
     */
    public void registerEvaluator(IEvaluator<?> evaluator) {
        String name = evaluator.getName();
        if (name == null || name.isEmpty()) {
            throw new IllegalArgumentException("Evaluator name cannot be null or empty");
        }
        evaluatorMap.put(name, evaluator);
    }
    
    /**
     * Get evaluator by keyword
     * @param keyword Search keyword
     * @return Evaluator instance
     */
    public IEvaluator<?> getEvaluatorByKeyword(String keyword) {
        if (keyword == null || keyword.isEmpty()) {
            return null;
        }
        return evaluatorMap.values().stream()
                .filter(evaluator -> evaluator.getName().toLowerCase().contains(keyword.toLowerCase()))
                .findFirst()
                .orElse(null);
    }
    
    /**
     * Get evaluator by name
     * @param name Evaluator name
     * @return Evaluator instance
     */
    public IEvaluator<?> getEvaluatorByName(String name) {
        if (name == null || name.isEmpty()) {
            return null;
        }
        return evaluatorMap.get(name);
    }
    
    /**
     * Get all evaluators
     * @return List of evaluators
     */
    public List<IEvaluator<?>> getAllEvaluators() {
        return List.copyOf(evaluatorMap.values());
    }
} 